package com.lottery.ruok.lottrey.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.TextView;

import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.dialog.PasswordDialog;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.GetRongUserInfoRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.GetProfileResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetRongUserInfoReponse;
import com.lottery.ruok.lottrey.userInfo.UserInfo;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import glideHelp.GlideHelper;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.Conversation;
import utils.StringUtils;
import utils.Utils;

/*
* 打赏操作页面
* */

public class GiveRewardActivity extends BaseActivity {


    public static final String EXTRA_CONVERSATION_TYPE = "extra_conversation_type";
    public static final String EXTRA_USER = "extra_user";
    public static final String EXTRA_TARGET_ID = "extra_target_id";
    @BindView(R.id.avatar)
    CircleImageView avatar;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.descp)
    TextView descp;
    @BindView(R.id.money)
    EditText money;
    @BindView(R.id.total_money)
    TextView totalMoney;
    @BindView(R.id.confirm)
    TextView confirm;
    private String conversationType;
    private io.rong.imlib.model.UserInfo userInfo;
    private String targetId;
    private String RongId;
    private String toUserName;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_give_reward);
        ButterKnife.bind(this);
        init();
        initView();
    }

    private void init() {
        Intent intent = getIntent();
        if (intent != null) {
            conversationType = intent.getStringExtra(EXTRA_CONVERSATION_TYPE);
            userInfo = intent.getParcelableExtra(EXTRA_USER);
            targetId = intent.getStringExtra(EXTRA_TARGET_ID);
            RongId=userInfo.getUserId();
            getUserName();
        }
        /**
         * 小数点后保留两位
         */
        money.addTextChangedListener(new TextWatcher()
        {
            public void afterTextChanged(Editable edt)
            {
            }

            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}

            public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {

                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        money.setText(s);
                        money.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    money.setText(s);
                    money.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        money.setText(s.subSequence(0, 1));
                        money.setSelection(1);
                        return;
                    }
                }
            }
        });

    }

    private void getUserName() {
        RetrofitBase.getRetrofit().create(GetRongUserInfoRequest.class).getResult(null,null, RongId)
                .compose(RxHelper.<GetRongUserInfoReponse>handleResult())
                .subscribe(new RxSubscribe<GetRongUserInfoReponse>(this) {
                    @Override
                    protected void _onNext(GetRongUserInfoReponse getRongUserInfoReponse) {
                        if (getRongUserInfoReponse!=null){
                  toUserName=          getRongUserInfoReponse.getList().get(0).getUsername();
                        }
                    }

                    @Override
                    protected boolean showDialog() {
                        return true;
                    }
                });
    }

    private void initView() {
        if (userInfo.getPortraitUri() != null) {
            GlideHelper.loadRoundImage(this,userInfo.getPortraitUri().toString(),avatar);
        }

        name.setText(userInfo.getName());
        descp.setText(UserInfo.getUsername() + "打赏了" + userInfo.getName() + "!");
        money.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
              /*  if(money.getText().length() == 0 || !Utils.isNumeric(money.getText().toString()) || Float.parseFloat(money.getText().toString()) == 0f){
                    confirm.setEnabled(false);
                    confirm.setTextColor(Color.parseColor("#7E33CD"));

                    totalMoney.setText(0 + "");
                } else {
                    confirm.setEnabled(true);
                    confirm.setTextColor(Color.parseColor("#ffffff"));

                    totalMoney.setText(money.getText().toString());
                }*/



                if(money.getText().toString().equals("")
                        || money.getText().toString().equals(".")
                        || Double.parseDouble(money.getText().toString()) == 0f){
                    confirm.setTextColor(Color.parseColor("#7E33CD"));
                    confirm.setEnabled(false);

                    totalMoney.setText(0 + "");
                } else {
                    confirm.setTextColor(Color.parseColor("#ffffff"));
                    confirm.setEnabled(true);

                    totalMoney.setText(Utils.saveTwoFormat(Double.parseDouble(money.getText().toString())));
                }




            }



        });
    }

    @OnClick(R.id.confirm)
    public void onViewClicked() {
        //sendAnalyticMsg("lottery_" + MobiComConversationFragment.ANALYTIC_VERSION + "_chat_reward_btn");

        updateAccount(new AfterUpdateAccount() {
            @Override
            public void afterUpdateAccount(GetProfileResponse getProfileResponse) {
                if (getProfileResponse.getUser().getWithdraw_password() == 1) {
                    PasswordDialog passwordDialog = new PasswordDialog();
                    Bundle bundle = new Bundle();
                    bundle.putInt(PasswordDialog.TYPE, 2);
                    bundle.putParcelable(PasswordDialog.TO_USER, userInfo);
                    bundle.putDouble(PasswordDialog.AMOUNT, StringUtils.parseDouble(totalMoney.getText().toString()));
                    bundle.putString(PasswordDialog.TARGET_ID, targetId);
                    bundle.putString(PasswordDialog.TO_USER_NAME, toUserName);
                    if (conversationType!=null){
                        bundle.putString(PasswordDialog.conversationType, conversationType);
                    }
                    passwordDialog.setArguments(bundle);
                    passwordDialog.show(getSupportFragmentManager(), null);
                } else {
                    Utils.showToast("您没有设置资金密码，请前往设置");
                }
            }
        }, true);
    }



}
